/****************************************************************************
 * Copyright 2009 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.filter.spi;

import com.gotobject.filter.internal.Objects;
import static com.gotobject.filter.internal.Objects.cast;
import static com.gotobject.filter.internal.Objects.raw;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * A class which will allow us to get generics info at runtime
 * if used correctly, derived from:
 * http://gafter.blogspot.com/2006/12/super-type-tokens.html
 * 
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public abstract class TypeLiteral <T> {
    private final Type type;

    /**
     * construct a TypeLiteral object.
     */
    protected TypeLiteral() {
        final Type superclass = noMissingTypeParam(getClass().getGenericSuperclass());
        type = cast(superclass, ParameterizedType.class).getActualTypeArguments()[0];
     }

    @Override
    public boolean equals(Object o) {
        return (o instanceof TypeLiteral) && Objects.equals(this.getType(), ((TypeLiteral) o).getType());
    }


    @SuppressWarnings({"unchecked"})
    public Class<T> getGenericClass(){
        final boolean   isClassInstance = getType() instanceof Class<?>;
        final Class<?>  rawType         = isClassInstance ? (Class<?>) getType() : raw(getType());
        return (Class<T>) rawType;
    }

    public Type getType() {
      return this.type;
    }

    public int hashCode() {
      return getType().hashCode();
    }
    
    
    public static Type noMissingTypeParam(Type superclass){
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }          
        return superclass;
    }

    @Override
    public String toString() {
        return getType().toString();
    }
}
